<template>
  <div class="userlist">
    <div class="content-header">
      <h1>用户信息管理</h1>
    </div>

    <div class="filter-container">
      <el-input placeholder="用户名" v-model="searchData" style="width: 200px;padding:20px" class="filter-item"></el-input>
      <el-button @click="filterData" class="dalfBut">查询</el-button>
      <el-button type="primary" class="butT" @click="dialogFormVisible = true">新建</el-button>
      <el-button @click="fromCommit()" style="position: relative;margin-left: 570px" type="danger">删除选中项</el-button>
    </div>

    <template>
      <el-table
          :data="users.filter(data => !search || data.userName.toLowerCase().includes(search.toLowerCase()))"
          stripe
          style="width: 100%"
          current-row-key="id"
          @selection-change="handleSelectionChange"
          height="450px">

        <el-table-column
            type="selection"
            style="margin-right: 100px"
            width="50">
        </el-table-column>


        <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center">
        </el-table-column>

        <el-table-column
            prop="userName"
            label="用户名"
            width=”300“
            align="center">
        </el-table-column>

        <el-table-column
            prop="password"
            label="密码"
            width=“300”
            align="center">
        </el-table-column>


        <el-table-column
            prop="role"
            label="角色"
            width="300"
            align="center">
        </el-table-column>

        <el-table-column
            prop="module"
            label="模块"
            width="300"
            align="center">
        </el-table-column>

        <el-table-column label="操作" align="center" width="300">

          <template slot-scope="scope">

            <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>

          </template>

        </el-table-column>

      </el-table>
    </template>


    <div class="updata-form">
      <el-dialog title="编辑用户信息" :visible.sync="dialogFormVisible4Edit" width="30%">
        <el-form :rules="rules2" ref="formData" >
          <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
            <el-input v-model="updateUser.userName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="新密码" :label-width="formLabelWidth" prop="formData">
            <el-input placeholder="请输入新密码" v-model="formData" class="filter-item" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" :label-width="formLabelWidth" prop="formDataConfirm">
            <el-input placeholder="请确认新密码" v-model="formDataConfirm" class="filter-item" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="模块" :label-width="formLabelWidth" prop="module">
            <el-select v-model="updateUser.module" placeholder="请选择模块" style="float: left" prop="module">
<!--              <el-option label="用户" value="用户"></el-option>-->
              <el-option label="节气" value="节气"></el-option>
              <el-option label="环境" value="环境"></el-option>
              <el-option label="旅游" value="旅游"></el-option>
              <el-option label="生态" value="生态"></el-option>
              <el-option label="气象科普" value="气象科普"></el-option>
<!--              <el-option label="系统管理员" value="系统管理员" v-if="isAdmin===true"></el-option>-->
            </el-select>
          </el-form-item>
          <el-button @click="dialogFormVisible4Edit = false">取 消</el-button>
          <el-button @click="handleUpdate" class="dalfBut" type="primary">确定</el-button>
        </el-form>
      </el-dialog>
    </div>


    <br/>
    <br/>

    <div class="add">
      <!--        添加弹出框 -->
      <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="31%">
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
            <el-input v-model="form.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
            <el-input v-model="form.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" :label-width="formLabelWidth" prop="passwordConfirm">
            <el-input v-model="form.passwordConfirm" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色" :label-width="formLabelWidth" prop="power">
            <el-select v-model="form.power" placeholder="请选择角色" style="float: left" prop="power">
<!--              <el-option label="用户" value="用户"></el-option>-->
              <el-option label="管理员" value="admin"></el-option>
              <el-option label="超级管理员" value="user"></el-option>
<!--              <el-option label="系统管理员" value="系统管理员" v-if="isAdmin===true"></el-option>-->
            </el-select>
          </el-form-item>
          <el-form-item label="模块" :label-width="formLabelWidth" prop="module">
            <el-select v-model="form.module" placeholder="请选择模块" style="float: left" prop="module">
<!--              <el-option label="用户" value="用户"></el-option>-->
              <el-option label="节气" value="节气"></el-option>
              <el-option label="环境" value="环境"></el-option>
              <el-option label="旅游" value="旅游"></el-option>
              <el-option label="生态" value="生态"></el-option>
              <el-option label="气象科普" value="气象科普"></el-option>
<!--              <el-option label="系统管理员" value="系统管理员" v-if="isAdmin===true"></el-option>-->
            </el-select>
          </el-form-item>
<!--          <el-form-item label="工务段名" :label-width="formLabelWidth" prop="note">-->
<!--            <el-select v-model="form.note" placeholder="请选择工务段" style="float: left">-->
<!--              <el-option v-for="o in segments" :label="o.segment" :value="o.segment" :key="o.segment"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-button @click="submitForm" class="dalfBut" type="primary">提交</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </el-form>
      </el-dialog>
    </div>

    <!--分页组件-->
    <div class="pagination-container">

      <el-pagination
          class="pagiantion"

          @current-change="handleCurrentChange"

          :current-page="pagination.currentPage"

          :page-size="pagination.pageSize"

          layout="total, prev, pager, next, jumper"

          :total="pagination.total">

      </el-pagination>

    </div>
  </div>
</template>
<script>

export default {
  name: "UserListComponent",
  data() {
    return {
      isAdmin:false,
      //主页面显示的用户信息
      multipleSelection: [],
      updateUser:[],
      segments: [],
      users: [],
      search: '',
      searchData: '',
      oldFormData: '',
      //控制添加弹出框
      dialogFormVisible: false,
      //控制编辑弹出框
      dialogFormVisible4Edit: false,
      //添加表单信息
      formData: '',
      formDataConfirm: '',
      rules: {//校验规则
        username: [
          // {validator: validateNamePass,  message: '用户为必填项', trigger: 'blur'},
          {min: 4, max: 50, message: '长度在 4 到 50 个字符', trigger: 'blur', required: true,}
        ],
        password: [
          // {validator: validatePwdPass,message: '密码为必填项', trigger: 'blur'},
          {min: 6, max: 250, message: '长度在 6 到 250 个字符', trigger: 'blur', required: true,}],
        // {min: 1, max: 200, message: '长度在 3 到 200 个字符', trigger: 'blur'}],
        power: [{required: true, message: '请选择', trigger: 'blur'}],
        module: {required: true, message: '请选择', trigger: 'blur'},
        passwordConfirm:{min: 6, max: 250, message: '长度在 6 到 250 个字符', trigger: 'blur', required: true},
        // formData: { trigger: 'blur', required: true,},
      },

      radio: '1',

      //控制删除提示框
      centerDialogVisible: false,

      // dialogTableVisible: false,

      form: {
        name: '',
        pwd: '',
        passwordConfirm: '',
        power: 'user',
        module: '节气'
      },
      formLabelWidth: '120px',
      //需要在需要检查的模板上填上":rules:xxxxx"，并在每一个需要检查的行中加入“prop”绑定数据。
      rules2: {
        // formData: { trigger: 'blur', required: true,},
      },
      pagination: {//分页相关模型数据
        currentPage: 1,//当前页码
        pageSize: 10,//每页显示的记录数
        total: 0,//总记录数
        truename: "",//查询条件
        name: "",
        ip: ""
      }
    };

  },
  mounted() {
    this.getAll();
    this.getSegments();
    if(localStorage.getItem('power')==='admin'){
      this.isAdmin=true
    }
  },

  methods: {
    //多选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    fromCommit() {
      this.$confirm("此操作永久删除当前信息，是否继续？", "提示", {type: "info"}).then(() => {
        var param = ''
        for (var i = 0; i < this.multipleSelection.length; i++) {
          param += this.multipleSelection[i].id + ','
          // param.append("nId",this.multipleSelection[i].nId)
        }

        // let params = new URLSearchParams();
        // let a = this.multipleSelection;

        this.$axios.post("/user/deleteUser?idList=" + param).then(
            (res) => {
              if (res.data.code === 200) {
                this.$message.success("删除成功");
              } else if (res.data.code === 401) {
                this.$message.error("无权限！");
              } else {
                this.$message.error("删除失败!");
              }
            }
        ).finally(() => {
          //2.重新加载数据
          this.getAll();
        })
        // this.getAll();
      }).catch(() => {
        this.$message.info("取消操作");
      });
    },

    //删除用户信息
    handleDelete(row) {
      this.$confirm("此操作永久删除当前信息，是否继续？", "提示", {type: "info"}).then(() => {
        this.$axios.post("/user/deleteUser?idList=" + row.id).then((res) => {
          if (res.data.code === 200) {
            this.$message.success("删除成功");
          } else if (res.data.code === 401) {
            this.$message.error("无权限！");
          } else {
            this.$message.error("数据同步失败，自动刷新");
          }
        }).finally(() => {
          //2.重新加载数据
          this.getAll();
        });
      }).catch(() => {
        this.$message.info("取消操作");
      });
    },

    //提交添加用户表单信息
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if(this.form.password === this.form.passwordConfirm){
            this.add();
          }else{
            this.$message.error("两次输入的密码不同！");
            return false;
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //重置表单
    resetForm(form) {
      this.$refs[form].resetFields();
    },
    //获取所有用户信息
    getAll() {
      //发送异步请求
      var param = '&power='+localStorage.getItem('power')
      this.$axios.get("/user/userList?curpage=" + this.pagination.currentPage + "&pagesize=" + this.pagination.pageSize + param).then((res) => {
        if (res.data.code === 401) {
          this.$message.error("无权限！");
        }
        this.pagination.total = res.data.data.total;
        this.users = res.data.data.records;
        console.log('----====')
        console.log(res.data.data.records)
        console.log(this.users)
      });
    },

    //切换页码
    handleCurrentChange(currentPage) {
      //修改页码值为当前选中的页码值
      this.pagination.currentPage = currentPage;
      //执行查询
      this.getAll();
    },
    //添加方法
    add() {
      let params = new FormData()
      params.append("userName", this.form.username);
      params.append('password', this.form.password);
      params.append('module', this.form.module);
      params.append('role', this.form.power)
      this.$axios.post("/user/register", params).then((res) => {
        if (res.data.code === 200) {
          this.$message.success("添加成功！")
        } else if (res.data.code === 401) {
          this.$message.error("无权限！");
        } else if (res.data.code === 400) {
          this.$message.error("只能拥有一个系统管理员")
        } else if (res.data.code === 500) {
          this.$message.error("服务器错误，请联系管理员")
        } else {
          this.$message.error("添加失败！")
        }
      }).finally(() => {
        this.dialogFormVisible = false;
        this.getAll();
      });
    },


    //提交编辑结果
    handleUpdate() {
      let params = new FormData()
      if(this.formData != '' || this.formData !=null || this.formData.length!=0){
        if(this.formData.length>20 && this.formData.length<4){
          this.$message.error("输入的密码不能超过20");
          return;
        }
        if(this.formData != this.formDataConfirm){
          this.$message.error("两次输入的密码不同！");
          return;
        }
        params.append('password', this.formData)
      }
      else if(this.formData === '' || this.formData === null || this.formData.length===0){
        params.append('password', this.updateUser.password)
      }
      // this.$refs.formData.validate((valid) => {
      //   if (valid) {
          params.append("role", this.updateUser.role);
          params.append('module', this.updateUser.module);
          params.append('userName', this.updateUser.userName)
          this.$axios.post("/user/modifyUser", params).then((res) => {
            if (res.data.code === 200) {
              this.$message.success("修改成功！")
            } else if (res.data.code === 401) {
              this.$message.error("无权限！");
            } else if (res.data.code === 500) {
              this.$message.error("服务器错误，请联系管理员")
            } else {
              this.$message.error("修改失败！")
            }
          }).finally(() => {
            //2.重新加载数据
            this.getAll();
            this.dialogFormVisible4Edit = false
          });
      //   }
      // });
    },
    //弹出编辑窗口
    handleEdit(row) {
      this.oldFormData = row.username
      // 使用 Object.assign() 方法创建一个新的对象 rowData，并将 scope.row 的属性复制到 rowData 中
      this.updateUser= Object.assign({}, row);
      console.log("rowrowrow")
      console.log(row)
      console.log(this.updateUser)
      console.log("=====")

      this.formData = ''
      this.dialogFormVisible4Edit = true
      // this.$axios.get("/fuid?id=" + row.id).then((res) => {
      //     if (res.data != null) {
      //         this.dialogFormVisible4Edit = true;
      //         this.formData = res.data;
      //         // alert(formData);
      //     } else {
      //         this.$message.error("数据同步失败，自动刷新");
      //     }
      // }).finally(() => {
      //     //2.重新加载数据
      //     this.getAll();
      // });
    },

    //取消操作，关闭弹窗
    cancel() {
      // this.dialogFormVisible = false;
      this.dialogFormVisible4Edit = false;
      this.$message.info("当前操作取消");
    },
    filterData() {
      let a = this.searchData;
      this.search = a;
    },
    // getSegments() {
    //   this.$axios.get("/segment/segmentList").then((res) => {
    //     this.segments = res.data.data
    //   });
    // }
  }
}

</script>
<style>
.filter-container {
  text-align: left;
}

.filter-item el-input {
  padding: 10px;
}


</style>
